package com.example.javafx.simple;

import javafx.application.Application;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;
import javafx.util.Duration;

public class ScheduledServiceExample extends Application {

    @Override
    public void start(Stage primaryStage) {
        Label label = new Label("Scheduled Task");

        // 创建 ScheduledService
        ScheduledService<Integer> service = new ScheduledService<>() {
            private int count = 0;

            @Override
            protected Task<Integer> createTask() {
                return new Task<>() {
                    @Override
                    protected Integer call() {
                        return ++count;  // 每次任务执行时增加计数
                    }
                };
            }
        };

        // 设置任务执行的周期，间隔 1 秒执行一次
        service.setPeriod(Duration.seconds(1));

        // 当任务执行完成时，更新 UI
        service.setOnSucceeded(event -> {
            int result = service.getValue();
            label.setText("Task executed: " + result);
        });

        // 启动服务
        service.start();

        Scene scene = new Scene(label, 200, 100);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}